package caiziyou.com.juc.volatiles;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData {
	volatile int number = 0;

	public void addT060() {
		this.number = 60;
	}
	
	public synchronized void addPlusPlus() {
		number++;
		ai.getAndIncrement();
	}
	
	AtomicInteger ai = new  AtomicInteger() ;
}

/**
 * 
 * @author caijianchao
 *
 */
public class VolatileDemo {

	public static void main(String[] args) {
		MyData myData = new MyData();
		for (int i = 0; i < 20; i++) {
			new Thread(()->{
				for (int j = 0; j < 1000; j++) {
					myData.addPlusPlus();
				}
			},String.valueOf(i)).start(); 
		}
		
		while(Thread.activeCount()>2) {
			Thread.yield();
		}
		System.out.println(Thread.currentThread().getName() +" final number number "+ myData.number);
		System.out.println(Thread.currentThread().getName() +" final number ai "+ myData.ai);
	}
	
	public void seeOkVolatile() {
		MyData myData = new MyData();

		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + "\t come in");
			try {
				TimeUnit.SECONDS.sleep(3);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			myData.addT060();
			System.out.println(Thread.currentThread().getName() + "\t update number value = " + myData.number);

		}, "AAA").start();

		while (myData.number == 0) {

		}

		System.out.println(Thread.currentThread().getName() + "\t mission is over,main get number " + myData.number);

	}
}
